<?php

namespace App\Http\Middleware;

use Closure;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Http\RedirectResponse;
use App\Models\Admin\SupplierConfiguration;
use App\Models\Admin\Supplier as SupplierModel;
use Illuminate\Support\Facades\DB;

class Supplier
{
    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure(Request): (Response|RedirectResponse) $next
     * @return Response|RedirectResponse
     * @throws Exception
     */
    public function handle(Request $request, Closure $next)
    {
        $host = $_SERVER['HTTP_SHABINGINX'];
        /** @var SupplierConfiguration|null $config **/
        $config = SupplierConfiguration::query()->firstWhere('domain',$host);
        if (!$config){
            return response(404,404);
        }
        /** @var SupplierModel|null $supplier**/
        $supplier = SupplierModel::query()->find($config->sid);
        if (!$supplier) {
            return response(404,404);
        }
        $request->attributes->set("supplier", $supplier);
        $connect = $config->registerDbConfig();
        if (!$connect) {
            return response(404,404);
        }
        $request->attributes->set("db", $connect);
        return $next($request);
    }
}
